package com.woke.adapter;

import android.databinding.DataBindingUtil;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.databinding.library.baseAdapters.BR;
import com.bean.Banner;

import com.jakewharton.rxbinding2.view.RxView;
import com.zhongcai.online.R;
import com.zhongcai.online.databinding.AdapterBannerItemBinding;


import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.functions.Consumer;


/**
 * 作者 ： 暗网
 * 创建时间：2017/3/14
 * 备注：
 */

public class AdapterBannerPager extends PagerAdapter {
    private List<Banner> banners;
    private int countNum = 0;

    public AdapterBannerPager(List<Banner> list) {
        this.banners = list;
    }

    private OnItemClickListener mItemClickListener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        mItemClickListener = listener;
    }

    @Override
    public int getCount() {
        return banners == null ? 0 : banners.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
//        View rootView = LayoutInflater.from(container.getContext())
//                .inflate(R.layout.adapter_banner_item, null);
        final AdapterBannerItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(container.getContext()), R.layout.adapter_banner_item, null, false);
        binding.setVariable(BR.banner, banners.get(position));
//        final AdapterBannerItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(container.getContext()), R.layout.adapter_banner_item, null, false);
////        binding.setVariable(BR.banner, banners.get(position));
        container.addView(binding.getRoot());
        RxView.clicks(binding.getRoot()).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                if (mItemClickListener != null) {
                    mItemClickListener.OnItemClick(binding.getRoot(), banners.get(position), position);
                }
            }
        });
        return binding.getRoot();
//        return rootView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//			super.destroyItem (container, position, object);
        container.removeView((View) object);
    }

    @Override
    public void notifyDataSetChanged() {
        countNum = getCount();
        super.notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(Object object) {
        if (countNum > 0) {
            countNum--;
            return POSITION_NONE;
        }
        return super.getItemPosition(object);
    }
}
